package com.jmpt.fangbohui.ui.personalcenter;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jmpt.fangbohui.Constants;
import com.jmpt.fangbohui.R;
import com.jmpt.fangbohui.bean.BrokerInfoBean;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean;
import com.jmpt.fangbohui.bean.LoginBean;
import com.jmpt.fangbohui.bean.UserEditIconBean;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval.date_city;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval.date_province;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval.date_zone;
import com.jmpt.fangbohui.bean.UserEditInfoBean;
import com.jmpt.fangbohui.dao.LoginSQLiteOperator;
import com.jmpt.fangbohui.http.AsyncHttp;
import com.jmpt.fangbohui.ui.base.BaseHeadActivity;
import com.jmpt.fangbohui.utils.CompressPhotoUtils;
import com.jmpt.fangbohui.utils.DebugLog;
import com.jmpt.fangbohui.utils.ImageLoaderHelper;
import com.jmpt.fangbohui.utils.ToastHelper;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;

public class EditBrokerInfoActivity extends BaseHeadActivity implements OnClickListener, OnItemSelectedListener {
	public static final String FILENAME = "fbhNewIcon.jpg";
	private String email;

	private String birth_y;

	private String birth_m;

	private String qq;

	private String sex;

	private String zoneid;

	private String httpParamsCityid;

	private String httpParamsProvinceid;

	
	private String serverZoneStr;

	private String oldpic;

	private String picUrl;
	
	@ViewInject(R.id.iv_user_info_edit_icon_real)
	private ImageView iv_user_info_edit_icon_real;
	
	@ViewInject(R.id.et_user_info_edit_nicheng_real)
	private EditText et_user_info_edit_nicheng_real;

	@ViewInject(R.id.sp_user_info_edit_sex_real)
	private Spinner sp_user_info_edit_sex_real;
	
	@ViewInject(R.id.et_user_info_edit_email_real)
	private EditText et_user_info_edit_email_real;

	@ViewInject(R.id.et_user_info_edit_qq_real)
	private EditText et_user_info_edit_qq_real;
	
	@ViewInject(R.id.sp_user_info_edit_province_real)
	private Spinner sp_user_info_edit_province_real;
	
	@ViewInject(R.id.sp_user_info_edit_place_real)
	private Spinner sp_user_info_edit_city_real;
	
	@ViewInject(R.id.sp_user_info_edit_zone_real)
	private Spinner sp_user_info_edit_zone_real;
	
	@ViewInject(R.id.tv_user_info_edit_servzone_real)
	private TextView tv_user_info_edit_servzone_real;
	
	@ViewInject(R.id.tv_user_info_edit_birthday_real)
	private TextView tv_user_info_edit_birthday_real;
	
	
	@ViewInject(R.id.rl_user_info_icon)
	private RelativeLayout rl_user_info_icon;
	
	public final static int SUCCESS = 200;
	public final static int FAILED = 202;
	
    private static int RESULT_LOAD_IMAGE = 1;
	
	public File newPic;
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			hideLoading();
			switch(msg.what){
			case SUCCESS:

				ToastHelper.ShowToast("操作成功", EditBrokerInfoActivity.this);
				finish();
			break;
			case FAILED:

				ToastHelper.ShowToast("操作失败", EditBrokerInfoActivity.this);
				
			break;
			}
			
		};
	};

	private String picturePath;

	private Bitmap compressBitmap;
	
	private String[] orign_serverZoneStr;
	
	private String serverZoneId = "";
	private ArrayList<String> sexList;
	private String gender;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_broker_info);
		ViewUtils.inject(this);
		getExtra();
		initView();
	}

	private void initView() {
		showTitle("经纪人修改信息");
		showBackButton(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		rl_user_info_icon.setOnClickListener(this);
	}

	private void getExtra() {
		Intent intent = getIntent();
		email = intent.getStringExtra("email");
		birth_y = intent.getStringExtra("birth_y");
		birth_m = intent.getStringExtra("birth_m");
		qq = intent.getStringExtra("qq");
		sex = intent.getStringExtra("sex");
		zoneid = intent.getStringExtra("zoneid");
		httpParamsCityid = intent.getStringExtra("cityid");
		httpParamsProvinceid = intent.getStringExtra("provinceid");
		
		
		serverZoneStr = intent.getStringExtra("serverZoneStr");
		DebugLog.i(serverZoneStr);
		DebugLog.i("httpParamsProvinceid"+httpParamsProvinceid);
		DebugLog.i("httpParamsCityid"+httpParamsCityid);
		DebugLog.i("zoneid"+zoneid);
		
		if(!TextUtils.isEmpty(serverZoneStr)){
			String[] split = serverZoneStr.split("、");
			for(int i = 0 ;i<split.length;i++){
				DebugLog.i(split[i]+"split"+i);
				servZoneLists.add(split[i]);
			}
		}
		tv_user_info_edit_servzone_real.setText(serverZoneStr);
		orign_serverZoneStr = serverZoneStr.split("、");
		oldpic = intent.getStringExtra("oldpic");
		picUrl = intent.getStringExtra("picUrl");
		dropDownBean = (EntryingHouseDropDownBean)intent.getSerializableExtra("dropDownBean");
		if (dropDownBean != null) {
			splitList(dropDownBean);
		}
		
		sexList = new ArrayList<String>();
		sexList.add("男");
		sexList.add("女");
		sp_user_info_edit_sex_real.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, sexList));
		sp_user_info_edit_sex_real.setOnItemSelectedListener(new OnItemSelectedListener() {



			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				gender = sexList.get(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
				
			}
		});
		int indexOf = sexList.indexOf(sex);
		sp_user_info_edit_sex_real.setSelection(indexOf);
		et_user_info_edit_email_real.setText(email);
		et_user_info_edit_qq_real.setText(qq);
		tv_user_info_edit_birthday_real.setText(birth_y+"年"+birth_m+"月");
		
		ImageLoaderHelper.displayImage(picUrl, iv_user_info_edit_icon_real);
	}
	private List<String> province;
	private List<String> city;
	private List<String> zone;
	private List<String> provinceIds;
	private List<String> cityIds;
	private List<String> zoneIds;
	private ArrayAdapter<String> provinceAdapter;
	private LoginSQLiteOperator oper;
	private EntryingHouseDropDownBean dropDownBean;
	private ArrayAdapter<String> cityAdapter;
	private ArrayAdapter<String> zoneAdapter;
	private void splitList(EntryingHouseDropDownBean bean) {
		province = new ArrayList<String>();
		city = new ArrayList<String>();
		zone = new ArrayList<String>();

		provinceIds = new ArrayList<String>();
		cityIds = new ArrayList<String>();
		zoneIds = new ArrayList<String>();

		result = bean.retval;
		for (date_province date_provinces : result.date_province) {
			province.add(date_provinces.ProvinceName);
			provinceIds.add(date_provinces.ProvinceID);
		}
		for (date_city date_citys : result.date_city) {
			city.add(date_citys.CityName);
			cityIds.add(date_citys.CityID);
		}
		
		for (date_zone element : bean.retval.date_zone) {
			zone.add(element.ZoneName);
			zoneIds.add(element.ZoneID);
			for(int i =0 ;i<orign_serverZoneStr.length;i++){
				
			}
		}
		provinceAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, province);
		sp_user_info_edit_province_real.setAdapter(provinceAdapter);
		sp_user_info_edit_province_real.setOnItemSelectedListener(this);
		sp_user_info_edit_city_real.setOnItemSelectedListener(this);
		sp_user_info_edit_zone_real.setOnItemSelectedListener(this);
		
		sp_user_info_edit_province_real.setSelection(provinceIds.indexOf(httpParamsProvinceid), true);
		sp_user_info_edit_city_real.setSelection(cityIds.indexOf(httpParamsCityid), true);
		sp_user_info_edit_zone_real.setSelection(zoneIds.indexOf(zoneid), true);
		
	}
	public void config(View view){
		//CHANGEBROKERINFO
		showLoading();
		LoginSQLiteOperator oper = new LoginSQLiteOperator(this);
		final List<String> querySessionId = oper.querySessionId();
		if(querySessionId.size() != 2){
			return;
		}
		HttpUtils utils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("AgentId",querySessionId.get(0));
		params.addBodyParameter("em",et_user_info_edit_email_real.getText().toString().trim());
		params.addBodyParameter("qq",et_user_info_edit_qq_real.getText().toString().trim());
		params.addBodyParameter("gender",gender);
		params.addBodyParameter("zoneid",zoneid);
		params.addBodyParameter("city",httpParamsCityid);
		params.addBodyParameter("provinceid",httpParamsProvinceid);
		params.addBodyParameter("serv_zone",serverZoneId);
//		params.addBodyParameter("serv_zone","1|2|");
		DebugLog.i("provinceid"+httpParamsProvinceid);
		DebugLog.i("cityid"+httpParamsCityid);
		DebugLog.i("zoneid"+zoneid);
		params.addBodyParameter("birth_y",birth_y);
		params.addBodyParameter("birth_m",birth_m);
		
		
		utils.send(HttpMethod.POST, Constants.URL.CHANGEBROKERINFO,params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				Message obtain = Message.obtain();
		    	obtain.what = FAILED;
		    	handler.sendMessage(obtain);
		    	DebugLog.i(arg1);
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				parser(arg0.result);
			}
		});
	}
	protected void parser(String result) {
		hideLoading();
		DebugLog.i(result);
		Gson gson = new Gson();
		UserEditInfoBean bean = gson.fromJson(result, UserEditInfoBean.class);
		
		if(bean != null){
			ToastHelper.ShowToast(bean.msg, this);
			if(Boolean.parseBoolean(bean.done)){
				finish();
			}
		}
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	 
	    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
	        Uri selectedImage = data.getData();
	        String[] filePathColumn = { MediaStore.Images.Media.DATA };
	 
	        Cursor cursor = getContentResolver().query(selectedImage,
	                filePathColumn, null, null, null);
	        cursor.moveToFirst();
	 
	        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	        picturePath = cursor.getString(columnIndex);
	        cursor.close();
	        
	        compressBitmap = CompressPhotoUtils.compressImage(BitmapFactory.decodeFile(picturePath));
	        CompressPhotoUtils.saveBitmap(compressBitmap);
	        iv_user_info_edit_icon_real.setImageBitmap(compressBitmap);
			uploadIcon(picturePath);
	    }
	}
	private List<String> servZoneIds = new ArrayList<String> ();
	private List<String> servZoneLists = new ArrayList<String> ();
	private Retval result;
	
	public  void servZone(View view){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		View inflate = View.inflate(this, R.layout.dialog_servzone, null);
		final LinearLayout ll_serv_zone = (LinearLayout) inflate
				.findViewById(R.id.ll_serv_zone);
		
		for(int i=0; i<zone.size(); i++)  
		{  
			CheckBox tempButton = new CheckBox(this);  
		    tempButton.setPadding(80, 0, 0, 0);                 // 设置文字距离按钮四周的距离   
		    if(zone == null || zone.size()==0){
		    	return;
		    }
		    for(int j = 0;j<servZoneLists.size();j++){
		    	if(servZoneLists.get(j).equals(zone.get(i)))
		    		tempButton.setChecked(true);
		    }
		    tempButton.setText(zone.get(i));  
		    ll_serv_zone.addView(tempButton, LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);  
		    tempButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					String temp = (((CheckBox)v).getText().toString().trim());
					if(servZoneLists.contains(temp)){
						servZoneLists.remove(temp);
					}else{
						servZoneLists.add(temp);
					}
				}
			});
		} 
		
		
		
		builder.setView(inflate);
		builder.setNegativeButton("取消", null);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				String tmepServZone = "";
				servZoneIds.clear();
				for(int i = 0;i<servZoneLists.size();i++){
					String temp = servZoneLists.get(i);
					DebugLog.i(temp);
					tmepServZone += temp +"、";
					String tempid = "";
					for(date_zone element : result.date_zone){
						if(element.ZoneName.equals(temp)){
							tempid = element.ZoneID;
						}
					}
					DebugLog.i(tempid);
					servZoneIds.add(tempid);
				}
				for(int i =0 ; i<servZoneIds.size();i++){
					serverZoneId += servZoneIds.get(i);
					if(i != servZoneIds.size()-1){
						serverZoneId += "|";
					}
				}
				tv_user_info_edit_servzone_real.setText(tmepServZone.substring(0, tmepServZone.length()-1));
				
			}
		});
		builder.show();
	}

	private void uploadIcon(String picturePath) {
		showLoading();
		HttpUtils utils = new HttpUtils();
		RequestParams params = new RequestParams();
		oper = new LoginSQLiteOperator(this);
		LoginBean query = oper.query();
		params.addBodyParameter("AgentId", query.retval.getAgentId());
		DebugLog.i(query.retval.getAgentId());
		params.addBodyParameter("oldpic", oldpic);
		File newIcon = new File(picturePath);
		DebugLog.i(newIcon.length() + "=length");
		params.addBodyParameter("pic", newIcon);
		utils.send(HttpMethod.POST, Constants.URL.BROKER_UPLOAD_ICON,params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						Message obtain = Message.obtain();
						obtain.what = FAILED;
						handler.sendMessage(obtain);
						DebugLog.i(arg1);
						hideLoading();
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						parserIcon(arg0.result);
					}
				});
	}
	protected void parserIcon(String result) {
		hideLoading();
		DebugLog.i("parserIcon"+result);
		Gson gson = new Gson();
		UserEditIconBean bean = gson.fromJson(result, UserEditIconBean.class);
		if(Boolean.valueOf(bean.done)){
			ToastHelper.ShowToast("上传头像成功", this);
		}else{
			ToastHelper.ShowToast("上传头像失败", this);
		}
	}


	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.rl_user_info_icon:
			Intent i = new Intent(
					Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					  
					startActivityForResult(i, RESULT_LOAD_IMAGE);
			break;
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		if (sp_user_info_edit_province_real == parent) {
			cityFilter(position);
		}
		if (sp_user_info_edit_city_real == parent) {
			zoneFilter(position);
		}
		if(sp_user_info_edit_zone_real == parent){
			zoneid = zoneIds.get(position);
			DebugLog.i("zone"+zone.get(position));
			DebugLog.i("zone"+zoneid);
		}
	}
	

	private void cityFilter(int position) {
		if(provinceIds == null|| provinceIds.size() == 0)
			return;
		httpParamsProvinceid = provinceIds.get(position);
		DebugLog.i(" 省份 select"+province.get(position));
		DebugLog.i(" 省份 select"+ httpParamsProvinceid);
		city.clear();
		cityIds.clear();
		for (date_city element : dropDownBean.retval.date_city) {
			if (element.ProvinceID.equals(httpParamsProvinceid)) {
				city.add(element.CityName);
				cityIds.add(element.CityID);
			}
		}
		if(cityAdapter == null){
			cityAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_spinner_dropdown_item, city);
			sp_user_info_edit_city_real.setAdapter(cityAdapter);
		}else{
			cityAdapter.notifyDataSetChanged();
		}
		sp_user_info_edit_city_real.setSelection(0);
		zoneFilter(0);
	}

	private void zoneFilter(int position) {
		if(cityIds == null|| cityIds.size() == 0)
			return;
		httpParamsCityid = cityIds.get(position);
		DebugLog.i("城市 select"+city.get(position));
		DebugLog.i("城市 select"+cityIds.get(position));
		zone.clear();
		zoneIds.clear();
		for (date_zone element : dropDownBean.retval.date_zone) {
			if (element.CityID.equals(httpParamsCityid)) {
				zone.add(element.ZoneName);
				zoneIds.add(element.ZoneID);
			}
		}
		if(zoneAdapter == null){
			zoneAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_spinner_dropdown_item, zone);
			sp_user_info_edit_zone_real.setAdapter(zoneAdapter);
		}else{
			zoneAdapter.notifyDataSetChanged();
		}
		sp_user_info_edit_zone_real.setSelection(0);
		zoneid = zoneIds.get(0);
		DebugLog.i("zone"+zone.get(0));
		DebugLog.i("zone"+zoneid);
		
	}
	
	public void editBirthday(View view) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		View inflate = View.inflate(this, R.layout.dialog_birthday, null);
		final NumberPicker np_dialog_birthday_year = (NumberPicker) inflate
				.findViewById(R.id.np_dialog_birthday_year);
		np_dialog_birthday_year.setMinValue(1950);
		np_dialog_birthday_year.setMaxValue(2015);
		np_dialog_birthday_year.setValue(2000);
		final NumberPicker np_dialog_birthday_month = (NumberPicker) inflate
				.findViewById(R.id.np_dialog_birthday_month);
		np_dialog_birthday_month.setMinValue(1);
		np_dialog_birthday_month.setMaxValue(12);
		builder.setView(inflate);
		builder.setNegativeButton("取消", null);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				birth_y = np_dialog_birthday_year.getValue() + "";
				birth_m = np_dialog_birthday_month.getValue() + "";
				tv_user_info_edit_birthday_real.setText(birth_y + "年" + birth_m
						+ "月");
			}
		});
		builder.show();
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		
	}
	
}
